package cn.new7as.cas5s.ui.record;


import static cn.new7as.cas5s.tool.util.Utils.CAMERA_A;
import static cn.new7as.cas5s.tool.util.Utils.getFileAbsolutePath;
import static cn.new7as.cas5s.tool.util.Utils.getList;
import static cn.new7as.cas5s.ui.apply.Info_ThirdActivity.ALBUM_A;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.http.listener.OnUpdateListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.new7as.cas5s.ui.slideshow.BaseActivity;
import cn.new7as.cas5s.R;
import cn.new7as.cas5s.databinding.ActivitySendordermsgBinding;
import cn.new7as.cas5s.tool.util.Utils;
import cn.new7as.cas5s.ui.easy.netapi.GetMailApi;
import cn.new7as.cas5s.ui.easy.netapi.HttpData;
import cn.new7as.cas5s.ui.easy.netapi.MsgSendApi;
import cn.new7as.cas5s.ui.easy.netapi.OrderApi;
import cn.new7as.cas5s.ui.easy.netapi.UpdateImageApi;
import cn.new7as.cas5s.ui.easy.netapi.UtrSendApi;
import cn.new7as.cas5s.ui.repay.SendsMsgadapter;


public class SendOrderMsgActivity extends BaseActivity {

    public static final int SORD = 88;
    private String[] rlphotp = new String[]{"Camera", "Album"};
    protected String[] needPermissions = {
            Manifest.permission.CAMERA,
    };
    private ActivitySendordermsgBinding binding;
    private List<UtrSendApi.Data> mDatas = new ArrayList<>();
    private List<String> mfileupDatas = new ArrayList<>();
    private List<String> mfileDatas = new ArrayList<>();
    private SendsMsgadapter utradapter;
    private SendsFileMsgadapter sendsFileMsgadapter;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySendordermsgBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setop("Send Message", true);
        initV();
        UtrSendApi.Data dataBean = new UtrSendApi.Data();

        mDatas.add(dataBean);

        utradapter = new SendsMsgadapter(mDatas, this);
        sendsFileMsgadapter = new SendsFileMsgadapter(mfileDatas, this);
        binding.monthGrid.setAdapter(utradapter);
        binding.filegride.setAdapter(sendsFileMsgadapter);
        getMail(getunique());
    }

    String name;
    String emailb;
    String whatsappb;

    void getMail(String to) {
        EasyHttp.get(this)
                .api(new GetMailApi(to)).request(new OnHttpListener<HttpData<GetMailApi.MailData>>() {
                    @Override
                    public void onHttpSuccess(@NonNull HttpData<GetMailApi.MailData> result) {
                        name = (result.getResult().name);
                        emailb = (result.getResult().email);
                        whatsappb = (result.getResult().whatsApp);

                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }

    String issuetype;

    @Override
    public void initV() {
        super.initV();

        issuetype = getIntent().getStringExtra("data");
        binding.orders.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SendOrderMsgActivity.this, SelectOrdersActivity.class);
                startActivityForResult(intent, SORD);
            }
        });
        binding.verifyme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendutr();
            }
        });
        binding.upfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFile();
            }
        });
        binding.message.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) binding.textnum.setText(s.length() + "/300");
            }
        });
    }

    private void sendutr() {
        String aa = binding.orders.getText().toString();
        if (aa.isEmpty()) {
            toa("please select an order");
            return;
        }
        String message = binding.message.getText().toString();

        show();
        EasyHttp.post(this)
                .api(new MsgSendApi(getunique(), name, emailb, whatsappb, Integer.parseInt(issuetype), aa, message, mfileupDatas, getList(mDatas))).request(new OnHttpListener<HttpData<OrderApi.OrderData>>() {

                    @Override
                    public void onHttpSuccess(@NonNull HttpData<OrderApi.OrderData> result) {
                        hide();
                        toa(getString(R.string.send_success));
                        finish();
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }
                });
    }


    void upload(File file) {
        show();
        EasyHttp.post(this)
                .api(new UpdateImageApi(file))
                .request(new OnUpdateListener<HttpData<String>>() {
                    @Override
                    public void onUpdateProgressChange(int progress) {

                    }

                    @Override
                    public void onUpdateSuccess(HttpData<String> result) {
                        hide();

                        if (upType == 0) {
                            UtrSendApi.Data dataBean = new UtrSendApi.Data();
                            dataBean.hjadkvsa = result.getResult();
                            if (mDatas.size() < 9) {

                                mDatas.add( mDatas.size()-1,dataBean);


                                utradapter.notifyDataSetChanged();

                            }
                        } else {
                            mfileDatas.add(filename);
                            mfileupDatas.add(result.getResult());
                            sendsFileMsgadapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onUpdateFail(@NonNull Throwable throwable) {
                        deal(throwable);
                    }

                });

    }


    public void showPhoto() {

        if (XXPermissions.isGranted(this, needPermissions)) {
            Utils.getcameimg(SendOrderMsgActivity.this, 0);
        } else
            XXPermissions.with(SendOrderMsgActivity.this)

                    .permission(needPermissions)

                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            Utils.getcameimg(SendOrderMsgActivity.this, 0);
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {

                        }
                    });
    }

    int upType;

    public void showPhoto2() {
        upType = 0;
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)

                .asBottomList("", rlphotp,
                        null, -1,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (position == 0) {
                                    showPhoto();
                                } else {
                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, ALBUM_A);
                                }

                            }
                        })
                .show();
    }

    private String filename;
    private String tno;

    @SuppressLint("MissingSuperCall")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            Bitmap bitmap;

            switch (requestCode) {
                case CAMERA_A:

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        bitmap = Utils.getBitmapFromUri(SendOrderMsgActivity.this, Utils.getUri(SendOrderMsgActivity.this));
                    } else {
                        bitmap = Utils.getBitmapFromUri(SendOrderMsgActivity.this, Uri.fromFile(Utils.imgFile));
                    }

                    upload(Utils.saveBitmapFile(getBaseContext(), bitmap));
                    break;
                case ALBUM_A:
                    bitmap = Utils.getBitmapFromUri(SendOrderMsgActivity.this, data.getData());

                    upload(Utils.saveBitmapFile(getBaseContext(), bitmap));
                    break;
                case SORD:

                    tno = data.getExtras().getString("tno");

                    binding.orders.setText(tno);
                    break;
                case 345:
                    if (data != null) {
                        if (resultCode == -1) {
                            if (data.getData() == null) {
                                return;
                            }
                            Uri uri = data.getData();
                            String path = getFileAbsolutePath(this, uri);
                            File file = new File(path);
                            filename = file.getName();
                            long fileSize = 0;


                            try {
                                fileSize = Utils.getFileSize(file);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (fileSize > 10 * 1024 * 1024) {
                                toa("The file cannot be larger than 10 M");
                                return;
                            }
                            if (path.endsWith(".txt") || path.endsWith(".pdf") || path.endsWith(".mkv") || path.endsWith(".mp4") || path.endsWith(".avi") || path.endsWith(".mov") || path.endsWith(".webm") || path.endsWith(".csv") || path.endsWith(".xls") || path.endsWith(".xlsx") || path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")) {
                                upload(file);
                            } else {
                                toa("The file format is not supported");
                            }
                        }

                    }
                default:
                    break;
            }
        }


    }

    public void deleFile(String pos,int poss) {
        Iterator<String> iterators = mfileupDatas.iterator();
        while (iterators.hasNext()) {
            String student = iterators.next();
            if (mfileupDatas.get(poss).equals(student)) {
                iterators.remove();
            }
        }
        Iterator<String> iterator = mfileDatas.iterator();
        while (iterator.hasNext()) {
            String student = iterator.next();
            if (pos.equals(student)) {
                iterator.remove();
            }
        }


        sendsFileMsgadapter.notifyDataSetChanged();
    }


    public void selectFile() {
        upType = 1;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "Select file upload"), 345);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a file manager.", Toast.LENGTH_SHORT).show();
        }
    }
}